package com.ruoyi.biz.api.config;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 微信参数配置
 */
@Component
public class WeChatConfig {

    public static final String ACCESS_TOKEN_KEY="wechat:accessToken";

    /**
     * 小程序ID
     */
    public static  String appId;

    /**
     * 小程序密钥
     */
    public static  String appSecret;


    private static RedisCache redisCache;



    public static String getAppId() {
        return appId;
    }

    @Value("${wechat.appId}")
    public  void setAppId(String appId) {
        WeChatConfig.appId = appId;
    }

    public static String getAppSecret() {
        return appSecret;
    }

    @Value("${wechat.appSecret}")
    public  void setAppSecret(String appSecret) {
        WeChatConfig.appSecret = appSecret;
    }

    public static RedisCache getRedisCache() {
        return redisCache;
    }

    @Autowired
    public  void setRedisCache(RedisCache redisCache) {
        WeChatConfig.redisCache = redisCache;
    }

    public static String getAuthUrl(){
        return "https://api.weixin.qq.com/sns/jscode2session?appid=" + getAppId() + "&secret=" + getAppSecret() + "&grant_type=authorization_code";
    }

    public static  String getAccessToken(){
        String accessToken = redisCache.getCacheObject(ACCESS_TOKEN_KEY);
        if (StringUtils.isBlank(accessToken)){
            accessToken = refreshAccessToken();
        }
        return accessToken;
    }

    public static synchronized String refreshAccessToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + getAppId() + "&secret="+getAppSecret();
        String result = HttpUtil.get(url);
        String accessToken = "";
        Integer expiresIn = 0;
        try {
            accessToken = JSONObject.parseObject(result).get("access_token").toString();
            expiresIn = Integer.valueOf(JSONObject.parseObject(result).get("expires_in").toString());
            redisCache.setCacheObject(ACCESS_TOKEN_KEY,accessToken,expiresIn, TimeUnit.SECONDS);
        }catch (Exception e){
            e.printStackTrace();
        }
        return accessToken;
    }
}
